/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.security.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.vacoor.nothing.web.controller.ControllerSupport;
import org.vacoor.nothing.web.entity.Variable;
import org.vacoor.nothing.web.service.ConfigurationManager;

import java.util.List;
import java.util.Map;

/**
 * @author vacoor
 */
@Controller
@RequestMapping("config")
public class ConfigController extends ControllerSupport {
    @Autowired
    ConfigurationManager configurationManager;

    @RequestMapping
    public String index(Map<String, Object> model) {
        Map<String/*group*/, List<Variable>> grouped = Maps.newHashMap();
        for (Variable var : configurationManager.findAll()) {
            String group = var.getGroup();
            List<Variable> vars = grouped.get(group);
            if (null == vars) {
                grouped.put(group, vars = Lists.newArrayList());
            }
            vars.add(var);
        }
        model.put("grouped", grouped);
        return "config/config";
    }

    @RequestMapping("create")
    public String create(Variable variable) {
        configurationManager.save(variable);
        return redirectViewPath("/");
    }

    @RequestMapping("save")
    public String save(@RequestParam Map<String, String> config) {
        Map<String, String> map = Maps.newHashMap();
        for (Map.Entry<String, String> entry : config.entrySet()) {
            String key = entry.getKey();
            if (null != key && key.startsWith("cfg_")) {
                map.put(key.substring(4), entry.getValue());
            }
        }

        configurationManager.update(map);
        return redirectViewPath("/");
    }

}
